<!--  -->
<script setup>
import { onMounted, ref } from 'vue'

const emit = defineEmits(['onSwitchOrder'])

const props = defineProps({
  orderType: { // { title: '最新', order: 'newest' } title唯一
    type: Array,
    default: () => []
  },
  moreOrderType: {
    type: Array,
    default: () => []
  }, initType: { // 初始选中的
    type: String,
    default: ''
  }
})

const currType = ref(props.initType || props.orderType[0].order)
const currExtraType = ref('')
const currExtraTitle = ref('更多')

onMounted(() => {
  // 检查初始类型是否在orderType中
  if (props.orderType.find(v => v.order === props.initType)) return
  // 可能在moreOrderType中, 寻找
  const find = props.moreOrderType.find(v => v.order === props.initType)
  if (find) currType.value = currExtraType.value = find.order, currExtraTitle.value = find.title
})

function switchOrder(v) {
  currType.value = v.order
  currExtraType.value = ''
  currExtraTitle.value = '更多'
  emit('onSwitchOrder', v.order)
}

function switchExtraOrder(v) {
  currType.value = currExtraType.value = v.order
  currExtraTitle.value = v.title
  emit('onSwitchOrder', v.order)
}
</script>

<template>
  <div class="rank-container">
    <div class="rank-item" v-for="(v, i) in orderType" :class="{ 'active-order': currType === v.order }"
      @click=switchOrder(v) :key="i"> {{ v.title }}
    </div>
    <div v-if="moreOrderType.length" class="rank-item extra-rank-item"
      :class="{ 'active-order': currType === currExtraType }">
      <div>{{ currExtraTitle }} </div>
      <ul class="dropdown-container">
        <li v-for="(v, i) in moreOrderType" :key="i" @click="switchExtraOrder(v)" class="dropdown-item">
          {{ v.title }}
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped lang="scss">
.rank-container {
  display: flex;
  align-items: center;
  border: 1px solid var(--border-secondary);
  border-radius: 2px;
  border-right: 0;

  .rank-item {
    padding: 4px 6px;
    border-right: 1px solid var(--border-secondary);
    cursor: pointer;

    &:hover {
      background-color: rgb(210, 225, 213);
    }
  }
}

.active-order {
  background-color: rgb(210, 225, 213);
}

.extra-rank-item {

  &:hover .dropdown-container {
    visibility: visible;
    opacity: 1;
  }

  &>div::after {
    border-bottom: 0;
    border-left: .3em solid #0000;
    border-right: .3em solid #0000;
    border-top: .3em solid;
    content: "";
    display: inline-block;
    margin-left: .255em;
    vertical-align: .255em;
  }
}

.dropdown-container {
  position: absolute;
  visibility: hidden;
  margin-top: 4px;
  opacity: 0;
  background-color: #dcf2e4;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  transition: all .3s ease-out;
}

.dropdown-item {
  transition: all .1s ease-out;
  padding: 5px 10px;
  cursor: pointer;

  &:hover {
    background-color: #84c99b;
  }
}
</style>
